package com.dmyang.p2pchat.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.dmyang.p2pchat.R;
import com.dmyang.p2pchat.adapter.ContactsListAdapter;
import com.dmyang.p2pchat.bean.User;
import com.dmyang.p2pchat.database.MySqlliteOpenHelper;
import com.dmyang.p2pchat.database.UserListDao;
import com.dmyang.p2pchat.thread.RecieveDataThread;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by brss on 2017/10/29.
 */

public class ListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
    private Context mContext;
    private ListView lv_simple;
    private List userList;
    private ContactsListAdapter contactsListAdapter;

    private RecieveDataThread recieveDataThread;

    //负责每秒发一个Message出去，handler收到后，就更新管理ListView的Adapter
    private Thread sendHandlerThread = new Thread(){
        @Override
        public void run() {
            while (true){
                android.os.Message msg = new android.os.Message();
                msg.obj = "whatever";
                msg.what = 1;
                handler.sendMessage(msg);
                try {
                    sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    //更新ui
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(android.os.Message msg) {

            UserListDao userListDao = new UserListDao(mContext);
            userList = userListDao.query();
            contactsListAdapter.refresh(userList);
            //contactsListAdapter.notifyDataSetChanged();
            //lv_simple.setAdapter(contactsListAdapter);
            //System.out.println(userList.size());
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        mContext = this;

        Handler handler = null;
        /*//建立udp服务器线程，后台监听。
        if (recieveDataThread==null){
            recieveDataThread = new RecieveDataThread(mContext,"192.168.1.102",9999);
            recieveDataThread.start();
        }
*/
        //找到listView
        lv_simple = (ListView)findViewById(R.id.lv_simple);

        //获取之前的聊天数据，用list封装,先造假数据（这里就不用Util了）
        userList = new ArrayList();
        //创建一个adapter
        contactsListAdapter = new ContactsListAdapter(mContext, userList);
        //将adapter设置给listView
        lv_simple.setAdapter(contactsListAdapter);

        //按钮绑定事件
        lv_simple.setOnItemClickListener(this);

        //数据库创建
        MySqlliteOpenHelper mySqlliteOpenHelper = new MySqlliteOpenHelper(mContext, "p2pchat", null, 1);
        //初始化数据库
        mySqlliteOpenHelper.getReadableDatabase();

        sendHandlerThread.start();

    }

    //listView条目点击时会调用该方法
    //adapterView:代表listview，view：代表点击的条目的那个view对象，position代表条目的位置，id：条目的id
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //获取条目bean对象中的数据（Ip+port）
        User user = (User) adapterView.getItemAtPosition(i);
        if (user == null){
            Toast.makeText(mContext,"id:"+i,Toast.LENGTH_SHORT).show();
        }

        String ipAndPort = user.getIp() + ":" + user.getPort();

        //跳转Activity

        //新建一个显式意图，第一个参数为当前Activity类对象，第二个参数为你要打开的Activity类
        Intent intent =new Intent(ListActivity.this,ChatActivity.class);

        //用Bundle携带数据
        Bundle bundle=new Bundle();
        //传递name参数为tinyphp
        bundle.putString("ipAndPort", ipAndPort);
        intent.putExtras(bundle);

        startActivity(intent);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.out.println("ListActivity的onDestroy执行了。");
        recieveDataThread = null;
    }
}
